/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vetxsoft.bean;

import java.io.IOException;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

/**
 *
 * @author Antonio
 */
@ManagedBean
@RequestScoped
public class AuthenticationBean implements Serializable {

    /**
     * Creates a new instance of AuthenticationBean
     */
    public AuthenticationBean() {
    }

    public String getUser() {
        String user = FacesContext.getCurrentInstance().getExternalContext().getRemoteUser();
        return (user == null || user.isEmpty()) ? "Usuario NO Autenticado " : user;
    }

//    public boolean isAdmin()
//    {
//        return FacesContext.getCurrentInstance().getExternalContext().isUserInRole("admin");
//    }
//    
//    public boolean isAgent()
//    {
//        return FacesContext.getCurrentInstance().getExternalContext().isUserInRole("agent");
//    }
    public boolean isRole(String role) {
        return FacesContext.getCurrentInstance().getExternalContext().isUserInRole(role);
    }

    public String logout() {
        try {

            HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
            request.logout();
            FacesContext.getCurrentInstance().getExternalContext().redirect("/vetxsoft/faces/index.xhtml");

            return "back";

        } catch (IOException ex) {
            Logger.getLogger(AuthenticationBean.class.getName()).log(Level.SEVERE, null, ex);
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, ex.getClass().getName(), ex.getMessage()));
            return null;

        } catch (ServletException ex) {
            Logger.getLogger(AuthenticationBean.class.getName()).log(Level.SEVERE, null, ex);
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, ex.getClass().getName(), ex.getMessage()));
            return null;
        }
    }
}
